package cn.jiyun.user.controller;


import cn.jiyun.user.service.RedisService;
import cn.jiyun.user.util.SendNoteUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "短信验证码登录")
@RestController
@RequestMapping(value = "/api/note")
public class SendNoteController {

    @Autowired
    private SendNoteUtil sendNoteUtil;

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/sendNote",method = RequestMethod.GET)
    public void sendNote(String phone, HttpServletResponse response){
        String template = "SMS_154950909";
        try {
            response.getWriter().write(sendNoteUtil.sendNoteMessgae(phone,template));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("手机验证码登录")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String phone,String authCode){
        //验证验证码
        if(verifyAuthCode(authCode,phone)){
            return"验证码错误";
        }
        return "登陆成功";
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = redisService.get( telephone);
        return authCode.equals(realAuthCode);
    }
}
